﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumTime.Helpers;
using ScrumTime.Models;
using ScrumTime.Services;

namespace ScrumTime.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            if (UserHelper.IsAuthorized(User.Identity, "Home Screen"))
            {
                return View();
            }                
            else                
                return RedirectToAction("Logon", "Account");
        }

        public ActionResult UpdateSession() {
            return new JsonResult();
        }


        public ActionResult ChangePassword(FormCollection collection)
        {
            try {
                String old_Password = collection.Get("oldPassword");
                String new_password = collection.Get("newPassword");
                String re_type_new_password = collection.Get("retypeNewPassword");
                
                if (new_password == re_type_new_password)
                {
                    AccountMembershipService membershipService = new AccountMembershipService();
                    System.Web.Security.MembershipUser user = getUser(User.Identity.Name, membershipService);
                    if (!user.ChangePassword(old_Password, new_password)) {
                        throw new Exception("An error occurred when trying to change the password.");    
                    };
                    
                }
                else {
                    throw new Exception("Passwords do not match.");
                }            
                
            }
            catch(Exception e){
                return Redirect(ErrorHelper.GetURLGeneralError(e.Message));
            }
            return View();
        }

        private System.Web.Security.MembershipUser getUser(String username, AccountMembershipService accountService)
        {
            System.Web.Security.MembershipUser resultado = null;
            foreach (System.Web.Security.MembershipUser user in accountService.GetAllUsers())
            {
                if (username == user.UserName)
                {
                    resultado = user;
                    break;
                }
            }
            return resultado;
        }
    }
}
